﻿using System;
using System.Windows.Forms;
using System.Collections;
using StockTrader.DAL.HastcAdapter.FileParser.Structure;
using StockTrader.DAL.HastcAdapter.FileParser;
using System.Drawing;
using StockTrader.DAL.HastcAdapter.FileMonitor.DataAccess;

namespace StockTrader.DAL.HastcAdapter.FileMonitor.BusinessLogic
{
    public class AsyncDataProcessor
    {
        DALclient client = new DALclient();
        private UpdateDB _invokeMe;
        private Label _lblState;
        private Type _objType;

        private delegate string UpdateDB();

        public AsyncDataProcessor(Label lblState, Type objType)
        {
            _lblState = lblState;
            _objType = objType;
            switch (objType.Name)
            {
                case "STS_MARKETINFO":
                    _invokeMe = new UpdateDB(DataAccessClient.UpdateMARKETINFO);
                    break;
                case "STS_STOCKSINFO":
                    _invokeMe = new UpdateDB(DataAccessClient.UpdateSTOCKINFO);
                    break;
                case "STS_TOP3_PRICE_A":
                    _invokeMe = new UpdateDB(DataAccessClient.UpdateTOP3A);
                    break;
                case "STS_TOP3_PRICE_B":
                    _invokeMe = new UpdateDB(DataAccessClient.UpdateTOP3B);
                    break;
                case "STS_ORDERS":
                    _invokeMe = new UpdateDB(DataAccessClient.UpdateORDERS);
                    break;
                case "STS_TRADING_RESULT":
                    _invokeMe = new UpdateDB(DataAccessClient.UpdateTRADINGRESULT);
                    break;
                default:
                    break;
            }

        }

        public void Execute()
        {
            //Update UI here
            MethodInvoker updateUIState = delegate
            {
                _lblState.BackColor = Color.Red;
            };
            if (_lblState.InvokeRequired)
                _lblState.Invoke(updateUIState);
            else
                updateUIState();
            _invokeMe.BeginInvoke(this.CallBack, null);
        }
        private void CallBack(IAsyncResult ar)
        {
            string listCount = _invokeMe.EndInvoke(ar);
            //Update UI here
            MethodInvoker updateUIState = delegate
            {
                _lblState.Text = listCount;
                if (ar.IsCompleted)
                    _lblState.BackColor = Color.Green;
            };
            if (_lblState.InvokeRequired)
                _lblState.Invoke(updateUIState);
            else
                updateUIState();
        }
    }
}
